package com.zy.aop.excerse1;

import java.util.concurrent.CountDownLatch;

/**
 * Created by zy on 2015/11/29.
 */
public class TestHarness {
    public long timeTasks(int nThreads, final Runnable task) {
        final CountDownLatch startGate = new CountDownLatch(1);
        final CountDownLatch endGate = new CountDownLatch(nThreads);

        for (int i = 0; i < nThreads; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        startGate.await();
                        try {
                            task.run();
                        } finally {
                            endGate.countDown();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
        long start = System.nanoTime();
        startGate.countDown();
        try {
            endGate.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long end = System.nanoTime();
        return end - start;
    }

    public static void main(String[] args) {
        Long executeTime = new TestHarness().timeTasks(5, new Runnable() {
            @Override
            public void run() {
                System.out.println("hello world,i begin to execute a task");
            }
        });
        System.out.println("current execute time is:" + executeTime);
    }

}
